package com.irishud.hudnavi;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.IPowerManager;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.amap.api.location.AMapLocation;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.NaviInfo;
import com.irishud.hudnavi.udp.UdpTxThread;
import com.irishud.hudnavi.wifi.WifiAdapter;
import com.irishud.protocol.BrightnessParam;
import com.irishud.protocol.DeviceSetting;
import com.irishud.protocol.MotorControlParam;
import com.irishud.protocol.NaviOnBoardModeParam;
import com.irishud.protocol.NaviParams;
import com.irishud.protocol.NaviUpdateInfo;
import com.irishud.protocol.ProtoMsg;

import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import protocol.ProtoFilter;
import tcp.TcpClientSocketThread;

/**
 * Created by Administrator on 2016/9/14.
 */
public class NaviFloatWindowService extends Service {
    String TAG = "NaviFloatWindowService";
    static NaviFloatWindowService instance;
    WindowManager windowManager;
    LayoutInflater inflater;
    // 浮窗控件
    RelativeLayout leftPanel;
    RelativeLayout righPanel;
    RelativeLayout bottomPanel;
    ImageView imgSpeedBgView;
    ImageView imgBottomBgView;
    Bitmap speedBgBitmap;
    Bitmap bottomBgBitmap;

    LinearLayout mCameraLayout;// 电子摄像限速标志

    ImageView ivNaviIconType; // 路口放大图
    TextView txtCurrentSpeed;  // 当前时速
    TextView txtNextRoadName;  // 下一个路口名称
    TextView txtNextRoadDistance; // 下一个路口距离

    Handler  mhandler = new Handler();
    StepingMotor stepingMotor;

    Timer heartbeatTimer;
    Timer onBoardNaviTimer;
    WifiManager wifiManager;
    View deviceStatusLayout;
    //Tcp comm
    TcpClientSocketThread tcpClientSocketThread;// Wifi模式 连接手机端 50002
    public TcpClientSocketThread phoneNaviDataSender; // OnBoardNaviDataSendingThread

    private UdpTxThread broadcastUdp;
    long lastWifiScanTime ;

    boolean OnBoardNavi = false; // 车载自主导航模式
    Sysconfig sysconfig;

    public static NaviFloatWindowService getInstance(){
        return  instance;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        init_configs();// 配置参数初始化

        EventBus.getDefault().register(this);
        wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        // 添加浮窗布局
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        inflater = (LayoutInflater) getApplicationContext()
                   .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rootLayout = null;
        if(BuildConfig.EN_MirrorNaviLayout){
            rootLayout = inflater.inflate(R.layout.ds3_mirror_main_layout0,null);
        }else{
            rootLayout = inflater.inflate(R.layout.ds3_main_layout,null);
        }
        addFloatWindow(rootLayout);
        View topLeft = rootLayout.findViewById(R.id.navi_speed_panel);
        View topRight = rootLayout.findViewById(R.id.navi_info_panel);
        initFloatWindow(topLeft,topRight);

        deviceStatusLayout= inflater.inflate(R.layout.device_connection_layout,null);
        addDeviceConnectionStatus(deviceStatusLayout);

        if(BuildConfig.DEBUG)
            addCloseButton();

        // 定位gps
        LocationAdapter.InitInstance(this); // TODO ???

        // 步进电机
        stepingMotor = new StepingMotor();

        connectToWifiAp(wifiManager,"wifi_test","11111111",null);

        // 设备心跳
        heartbeatTimer =new Timer();
        heartbeatTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                ProtoMsg protoMsg = new ProtoMsg("device.heartbeat","");
                if(tcpClientSocketThread!=null){
                    tcpClientSocketThread.send(protoMsg.toBytes());
                    Log.w(TAG,"============> Device heart beat alive!(Client Mode)");
                }
            }
        },1000,1*1000);// 每隔3s发送一次心跳

        lastWifiScanTime = System.currentTimeMillis();
        final ProtoFilter protoFilter = new ProtoFilter();
        protoFilter.setLisenter(new ProtoFilter.OnFilterResultListener() {
            @Override
            public void OnMessageReceive(ByteBuffer bb) {
                    //TODO parse ProtoMsage byte[]
                // 解析消息
                System.out.println("====> head:" +bb.getShort());
                System.out.println("---- total_len:" +bb.getInt());
                System.out.println("---- msg_type:" +bb.getInt());
                System.out.println("---- msg_id:" +bb.getLong());

                int action_len = bb.getInt();
                System.out.println("---- action_len:" +action_len);
                byte[] str_byte= new byte[action_len];
                bb.get(str_byte, 0, action_len);
                String action_string = new String(str_byte);
                System.out.println("action string:"+new String(str_byte));

                int data_len = bb.getInt();
                System.out.println("---- data_len:" +data_len);
                byte[] data_byte= new byte[data_len];
                bb.get(data_byte, 0, data_len);
                System.out.println("data string:"+new String(data_byte));
                handleProtoMsg(action_string,data_byte);
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                tcpClientSocketThread = new TcpClientSocketThread("192.168.43.1",50002);
                tcpClientSocketThread.setReceiveListener(new TcpClientSocketThread.ReceiveListener() {
                    @Override
                    public void OnDataReceive(byte[] data, int len) {
                        protoFilter.onDataFiltering(data,len); // 添加到协议过滤
                    }
                });
                tcpClientSocketThread.setStateListener(new TcpClientSocketThread.TcpClientStateListener() {
                    @Override
                    public void onTcpClientReconnect(TcpClientSocketThread socketThread,String ip, int port) {
                        Log.e(TAG,"tcp client try to reconncet...");
                        mhandler.post(new Runnable() {
                            @Override
                            public void run() {
                                deviceStatusLayout.setVisibility(View.VISIBLE);
                            }
                        });

                        if(!wifiManager.isWifiEnabled()){
                            Log.i(TAG,"========== open wifi==============>");
                            wifiManager.setWifiEnabled(true); // 重连时候尝试打开wifi，因为有时候wifi是关闭的!
                        }

                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                        Log.i(TAG,"CURRENT ----> WIFI CONNECT INFO:"+wifiInfo.toString());
                        if(wifiInfo.getBSSID()==null || wifiInfo.getBSSID().equals("00:00:00:00:00:00") || wifiInfo.getSSID().contains("unknown")){
                            Log.i(TAG," lost wifi connection! ");
                            long now = System.currentTimeMillis();
                            long delta = now - lastWifiScanTime;
                            connectToWifiAp(wifiManager,"wifi_test","11111111",null);
                            if(delta > 15*1000){
                                wifiManager.startScan();
                                Log.e(TAG,"start wifi scanning...");
                                lastWifiScanTime = System.currentTimeMillis();
                            }
                        }
                    }
                    @Override
                    public void onTcpClientConnectionOk(TcpClientSocketThread socketThread,String serverIp, InetAddress ownIp, int port) {
                        mhandler.post(new Runnable() {
                            @Override
                            public void run() {
                                deviceStatusLayout.setVisibility(View.GONE);
                            }
                        });

                        Log.e(TAG,":allocate-----> 分配的IP地址："+ownIp.getHostAddress());
                    }

                    @Override
                    public void onTcpClientFailedConnection(TcpClientSocketThread socketThread,String ip, int port) {
                        mhandler.post(new Runnable() {
                            @Override
                            public void run() {
                                deviceStatusLayout.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                });
                tcpClientSocketThread.connect();
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                phoneNaviDataSender = new TcpClientSocketThread("192.168.43.1",19000);// 发送车载导航数据
                phoneNaviDataSender.connect();
            }
        }).start();

        // broadcastUdp = new UdpTxThread("255.255.255.255",18000);
        // 电子罗盘传感器信息
//        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//        sensorManager.registerListener(new CompassEventListener(),
//                sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
//                SensorManager.SENSOR_DELAY_NORMAL);
    }

    // 罗盘方位角数据
    class CompassEventListener implements SensorEventListener{

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
                float degree = event.values[0];
                // Log.i(TAG,"---------> sensor orientation 发送到 AR 电子罗盘方位角：x="+degree);
//                broadcastUdp.enqueue(sendOrientationAngle
//                        (new double[]{event.values[0],event.values[1],event.values[2]}));// 发送数据到AR设备去
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }

    interface  WifiConnectionStateCallback{
        void onWifiConnected();
    }

    public  ByteBuffer sendOrientationAngle(double[] angles){
        byte[] headbyte = new byte[3];
        int len = angles.length * 8 + 1;
        headbyte[0] = (byte) (len & 0xFF );
        headbyte[1] = (byte) ( (len >> 8 ) & 0xFF );

        ByteBuffer byteBuffer = ByteBuffer.allocate(angles.length*8 + 3);
        headbyte[2] = 5;// cmd

        byteBuffer.put(headbyte);
        for(int i=0;i<angles.length;i++) {
            byteBuffer.put(ByteUtil.getBytes(angles[i]));
        }
        return byteBuffer;
    }

    void initFloatWindow(View topLeft,View topRight){
        // 左面板
        //View leftPanel = inflater.inflate(R.layout.ds3_float_window_speed_layout,null);
        txtCurrentSpeed = (TextView)topLeft.findViewById(R.id.txt_current_speed);
        //addLeftPanel(leftPanel);

        // 右面板
        //View rightPanel = inflater.inflate(R.layout.ds3_float_window_info_layout,null);
        ivNaviIconType = (ImageView)topRight.findViewById(R.id.img_navi_icon_type);// 导航转向图标类型
        txtNextRoadName =(TextView)topRight.findViewById(R.id.txt_next_road_name); // 下一个路口
        txtNextRoadDistance = (TextView)topRight.findViewById(R.id.txt_next_road_distance);// 下一个路口距离
        mCameraLayout = (LinearLayout)topRight.findViewById(R.id.img_camera_type);
        // addRightPanel(rightPanel);

        // 底部面板
        // View bottmPanel = inflater.inflate(R.layout.ds3_float_window_bottom_layout,null);
        //addBottomPanel(bottmPanel);
    }
    // 处理通信协议
    void handleProtoMsg(String action,byte[] jsonBytes){
        String content = new String(jsonBytes,0,jsonBytes.length) ;
        try {
        }catch (JSONException e){
            Log.e(TAG,"jSON parse error:"+e.getMessage());
            Log.i(TAG,"jSON string="+content);
            return;
        }

        if(action.equals("updateNaviSpeed")){
            final NaviUpdateInfo updateInfo = JSON.parseObject(content,NaviUpdateInfo.class);
            // TODO 更新当前速度
            Log.i(TAG,"-------------->更新当前速度");
            mhandler.post(new Runnable() {
                @Override
                public void run() {
                    updateCurrSpeed(updateInfo.speed);
                }
            });
        }

        if(action.equals("updateNaviInfo")){
            final NaviUpdateInfo updateInfo = JSON.parseObject(content,NaviUpdateInfo.class);
            // TODO 更新当前
            mhandler.post(new Runnable() {
                @Override
                public void run() {
                    // 下一个路口信息
                    updateNextTurnInfo(
                            updateInfo.nextRoadName,
                            String.valueOf(NaviUtil.getFriendlyLength(updateInfo.nextRoadDistance)),
                            updateInfo.nextTurnIcon);

                    upadateCameraInfo(mCameraLayout,
                            updateInfo.cameraType,
                            String.valueOf(updateInfo.speedLimit),
                            String.valueOf(updateInfo.cameraDistance));
                }
            });
        }

        if(action.equals("switchToWifiMode")){
        }
        // 调整屏幕亮度
        if(action.equals("adjust_light")){
            final BrightnessParam brightness = JSON.parseObject(content,BrightnessParam.class);
            int value = brightness.value;
            Log.i(TAG,"adjust brightness value="+value);
            setIntScreenBrightness2(value);
            sysconfig.setSystemBrightness(value);// 保存系统设置的亮度
        }

        if(action.equals("set_navi_on_board")){
            NaviOnBoardModeParam how = JSON.parseObject(content,NaviOnBoardModeParam.class);
            OnBoardNavi = how.navi_on_board;
            Log.i(TAG,"------> navi on board :"+how.navi_on_board);
            if(OnBoardNavi){
                Log.i(TAG," 车载导航模式!");
            }else{
                Log.i(TAG," 手机导航模式!");
            }
        }


        if(action.equals("start_on_board_navi")){
            NaviParams naviParams = JSON.parseObject(content,NaviParams.class);
            Log.i(TAG," ---------------start on board navi ---------> 车载导航模式! protoMsg.content:"+content);
            NaviAdapter.InitInstance().startNaviFrom(naviParams);
        }

        if(action.equals("stop_on_board_navi")){
            Log.i(TAG," ---------------stop on board navi ---------> 车载导航模式!");
            NaviAdapter.InitInstance().Close();
        }

        if(action.equals("get_device_settings")){// 查询设备设置信息
            DeviceSetting deviceSetting = new DeviceSetting();
            deviceSetting.onBoardNavi = sysconfig.isOnBoardNavi();
            deviceSetting.screenBrightness = sysconfig.getSystemBrightness();
            ProtoMsg response = new ProtoMsg("device.settings",JSON.toJSONString(deviceSetting));
            tcpClientSocketThread.send(response.toBytes());
        }

        if(action.equals("set_motor1_rotate") || action.equals("set_motor2_rotate")){
            MotorControlParam motorControlParam = JSON.parseObject(content,MotorControlParam.class);
            Log.e(TAG,"----->马达控制："+action + " param:"+motorControlParam.toString());
            try {
                FileWriter fileWriter = new FileWriter("/sys/bus/platform/drivers/commom2phase/rwreg");
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(motorControlParam.direction);
                stringBuilder.append(" ");
                stringBuilder.append(motorControlParam.motorId);
                fileWriter.write(stringBuilder.toString());
                fileWriter.close();
            } catch (IOException e) {
                Log.e(TAG,"error motor control:"+e.getMessage());
            }
        }
    }

    void startWifAp(){
        Log.i(TAG,"============ 打开设备热点 =========");
        String ssid = "ds3_wifi";
        String password = "12345678";
        WifiAdapter wifiAdapter = WifiAdapter.InitInstance(this,
                ssid,password);
        wifiAdapter.CloseWifiAp();
        WifiAdapter.OpenWifiThread thread = wifiAdapter.new OpenWifiThread(this);
        thread.start();
    }

    private void connectToWifiAp(WifiManager mWifiManager,
                                 String netName,
                                 String netPwd,
                                 WifiConnectionStateCallback callback) {
        if(!mWifiManager.isWifiEnabled()){
            Log.i(TAG,"WIFI 处于关闭状态，正打开wifi");
            mWifiManager.setWifiEnabled(true);
        }
        //配置Wifi信息
        WifiConfiguration wifiCong = wifiConfig(netName, netPwd);
        // 将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态，成功返回ID，否则为-1
        int network = mWifiManager.addNetwork(wifiCong);
        Log.e(TAG, "network="+network);
        if (network != -1) {
            boolean connectWifiok = wifiManager.enableNetwork(network, true);
            if (connectWifiok) {
                Log.w(TAG,"wifi 连接成功！");
                if(callback!=null){
                    callback.onWifiConnected();
                }
            } else {
                Log.w(TAG,"wifi 连接失败！");
            }
        } else {
            Log.w(TAG,"wifi 网络连接错误 errocode:-1");
        }
    }

    private WifiConfiguration wifiConfig(String netName, String netPwd) {
        WifiConfiguration wifiCong = new WifiConfiguration();
        wifiCong.SSID = "\"" + netName + "\"";// \"转义字符，代表"
        wifiCong.preSharedKey = "\"" + netPwd + "\"";// WPA-PSK密码
        wifiCong.hiddenSSID = false;
        wifiCong.status = WifiConfiguration.Status.ENABLED;
        return wifiCong;
    }

    private void addFloatWindow(View layout){
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        layoutParams.x = 0;
        layoutParams.y = 120;
        layoutParams.width = 800;
        layoutParams.height = 240;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        windowManager.addView(layout,layoutParams);
    }

    private void addDeviceConnectionStatus(View layout){
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        layoutParams.x = 300;
        layoutParams.y = 160;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        windowManager.addView(layout,layoutParams);
    }

    // 左面版 车速信息
    private void addLeftPanel(View layout){
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        layoutParams.x = 100;
        layoutParams.y = 180;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        windowManager.addView(layout,layoutParams);
    }

    private void addRightPanel(View layout){
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        layoutParams.x = 530;
        layoutParams.y = 200;
        layoutParams.width = 170;
        layoutParams.height = 150;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        windowManager.addView(layout,layoutParams);
    }

    private void addBottomPanel(View  layout){
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
        layoutParams.x = 0;
        layoutParams.y = 300;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        windowManager.addView(layout,layoutParams);
    }

    private void addCloseButton(){
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.format = PixelFormat.TRANSLUCENT;
        layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        layoutParams.x = 0;
        layoutParams.y = 400;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        Button closeBtn = new Button(this);
        closeBtn.setText("X");
        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopSelf();
                Process.killProcess(Process.myPid());
            }
        });
        windowManager.addView(closeBtn,layoutParams);
    }

    // 速度
    private void updateCurrSpeed(int speed){
        txtCurrentSpeed.setText(String.valueOf(speed));
    }

    // 电子狗
    private void updateSpeedCameraView(Context context, LinearLayout cameraLayout, NaviInfo naviinfo){
        setCameraType(this, mCameraLayout, naviinfo);
    }

    int cnt = 0;
    private void setCameraType(Context context, LinearLayout cameraLayout, NaviInfo naviinfo) {
        int cameraType = naviinfo.getCameraType();
        String speed = naviinfo.getLimitSpeed() + "";
        String distance = naviinfo.getCameraDistance() + "";
        upadateCameraInfo(cameraLayout,cameraType,speed,distance);
    }

    /**
     * 导航测速限速信息
     * @param cameraLayout
     * @param cameraType
     * @param speedLimit
     * @param cameraDistance
     */
    private void upadateCameraInfo(LinearLayout cameraLayout,int cameraType,
                                   String speedLimit,String cameraDistance){
        Log.i(TAG,"-------------->测速,限速摄像头信息");
        LinearLayout inflateLayout = null;
        Button button = null;
        // 先移除所有图标
        cameraLayout.removeAllViews();
        // cameraType - 电子眼类型 0-测速摄像 1-监控摄像 2-闯红灯拍照 3-违章拍照 4-公交专用道摄像头 5-应急车道拍照
        cnt++; // for test
        switch (cameraType) {
            // 0-测速摄像
            case 0:
                Log.e(TAG,"0-测速摄像");
                inflateLayout = (LinearLayout) inflater.inflate(R.layout.ds3_camera_type0, null);
                button = (Button) inflateLayout.findViewById(R.id.camera_type_image);
                button.setText(speedLimit);
                //Log.e(TAG,"测速摄像");
                break;
            // 1-监控摄像
            case 1:
                Log.e(TAG,"1-监控摄像");
                inflateLayout = (LinearLayout) inflater.inflate(R.layout.ds3_camera_type1, null);
                button = (Button) inflateLayout.findViewById(R.id.camera_type_image);
                button.setText(cameraDistance);
                //Log.e(TAG,"监控摄像");
                break;
            // 2-闯红灯拍照
            case 2:
                break;
            // 3-违章拍照
            case 3:
                break;
            // 4-公交专用道摄像头
            case 4:
                break;
            // 5-应急车道拍照
            case 5:
                break;
            default:
                break;
        }
        // 最后动态添加布局
        if (inflateLayout != null) {
            cameraLayout.addView(inflateLayout);
        }else{
            // Log.e(TAG,"inflateLayout == null!!!");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        instance = this;
        EventBus.getDefault().unregister(this);
    }

    // 初始化所有系统配置参数
    void init_configs(){
        // 系统亮度
        sysconfig = new Sysconfig(this);
        int currentBrightness = sysconfig.getSystemBrightness();
        setIntScreenBrightness2(currentBrightness);
        // 当前导航模式
        OnBoardNavi = sysconfig.isOnBoardNavi();
    }

    private void setIntScreenBrightness2(int brightness){
        float value = (brightness - 128f) / 128f;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
        String result = df.format(value);//返回的是String类型
        Log.w(TAG,"setIntScreenBrightness2() float value="+result);
        final IPowerManager mPower;
        mPower = IPowerManager.Stub.asInterface(ServiceManager.getService("power"));
        try {
            float result_float =Float.parseFloat(result);
            Log.w(TAG,"setIntScreenBrightness2() result_float="+result_float);
            mPower.setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(result_float);
        } catch (RemoteException ex) {
            Log.w(TAG,"setIntScreenBrightness2() error="+ex.getMessage());
        }
    }


    @Subscribe
    public void handleBrightnessEvent(BrightnessEvent event){
    }

    private int getIconType(Context context, int type) {
        String strId = "icon_type_" + type;
        return getDrawableId(context, strId);
    }

    private int getDrawableId(Context paramContext, String paramString) {
        return paramContext.getResources().getIdentifier(paramString, "drawable", paramContext.getPackageName());
    }

    // 下个路口信息
    void updateNextTurnInfo(String nextRoadName,String dist,int iconType){
        Log.i(TAG,"-------------->更新下个路口信息");
        txtNextRoadName.setText(nextRoadName);
        txtNextRoadDistance.setText(dist);
        ivNaviIconType.setBackgroundResource(getIconType(this,iconType));
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleNaviRequest(NaviEvent naviEvent){

        if(naviEvent.id == NaviEvent.StartNavi){
            Log.e(TAG,"-------------> 浮窗开始接收导航");
            NaviParams params = (NaviParams) naviEvent.eventData;
            NaviAdapter.InitInstance().startNaviFrom(params);
        }

        if(naviEvent.id == NaviEvent.StopNavi){
            Log.e(TAG,"-------------> 浮窗关闭导航");
            NaviAdapter.InitInstance().closePreviousNaviTasks();
        }

        if(naviEvent.id == NaviEvent.UpdateNaviInfo){
            NaviInfo info = (NaviInfo)naviEvent.eventData;
            int distance = info.getCurStepRetainDistance();
            int iconType = info.getIconType();
            String nextRoadNamee = info.getNextRoadName();
            String nextRoadAddress = info.getCurrentRoadName();
            updateNextTurnInfo(nextRoadNamee,NaviUtil.formatKM(distance),iconType);
            Log.e(TAG,"-------------> 更新导航过程信息，距离:"+distance+" ,转向图标icon"+iconType);
            setCameraType(this, mCameraLayout, info); // 电子眼监控提示信息
        }

        if(naviEvent.id == NaviEvent.UpdateNaviLocationInfo){
            AMapNaviLocation location = (AMapNaviLocation)naviEvent.eventData;
            txtCurrentSpeed.setText(String.valueOf((int)location.getSpeed()));
            Log.e(TAG,"-------------> 导航速度："+location.getSpeed());
        }

        if(naviEvent.id == NaviEvent.ShowCrossRoadInfo){
            AMapNaviCross aMapNaviCross = (AMapNaviCross) naviEvent.eventData;
            //ivNaviIconType.setImageBitmap(aMapNaviCross.getBitmap());
        }

        if(naviEvent.id == NaviEvent.HideCrossRoadInfo){
            //ivNaviIconType.setVisibility(View.GONE);
        }
    }

    @Subscribe
    public void handleCanBusEvent(CanBusEvent event){
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onLocationUpdate(AMapLocation location) {
        if(OnBoardNavi){
            float currentSpeed = location.getSpeed();
            txtCurrentSpeed.setText(String.valueOf((int)currentSpeed));// 当前车速信息
        }
    }
}
